package com.ruoyi.pos.service.impl.payment;

import com.ruoyi.pos.domain.payment.PosPaymentType;
import com.ruoyi.pos.domain.dto.payment.request.PaymentTypeQueryRequest;
import com.ruoyi.pos.domain.dto.payment.response.PaymentTypeResponse;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.mapper.payment.PosPaymentTypeMapper;
import com.ruoyi.pos.service.payment.IPosPaymentTypeService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * POS支付方式Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Service
@Transactional(transactionManager = "posTransactionManager")
public class PosPaymentTypeServiceImpl implements IPosPaymentTypeService {

    @Autowired
    private PosPaymentTypeMapper posPaymentTypeMapper;

    /**
     * 查询单个支付方式信息
     * 支持根据ID、编码查询
     * 
     * @param request 查询请求
     * @return 支付方式信息
     */
    @Override
    public PaymentTypeResponse getPaymentType(PaymentTypeQueryRequest request) {
        PosPaymentType paymentType = null;
        
        if (request.getTypeId() != null) {
            paymentType = posPaymentTypeMapper.selectPosPaymentTypeById(request.getTypeId());
        } else if (StringUtils.isNotEmpty(request.getTypeCode())) {
            paymentType = posPaymentTypeMapper.selectPosPaymentTypeByCode(request.getTypeCode());
        }
        
        if (paymentType == null) {
            return null;
        }
        
        return convertToResponse(paymentType);
    }

    /**
     * 分页查询支付方式列表
     * 
     * @param request 查询请求
     * @return 分页响应
     */
    @Override
    public BasePageResponse<PaymentTypeResponse> queryPaymentTypes(PaymentTypeQueryRequest request) {
        PosPaymentType paymentType = new PosPaymentType();
        paymentType.setTypeId(request.getTypeId());
        paymentType.setTypeCode(request.getTypeCode());
        paymentType.setTypeName(request.getTypeName());
        paymentType.setIsEnabled(request.getIsEnabled());
        
        List<PosPaymentType> paymentTypes = posPaymentTypeMapper.selectPosPaymentTypeList(paymentType);
        List<PaymentTypeResponse> responses = paymentTypes.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
        
        return new BasePageResponse<>(responses, paymentTypes.size());
    }

    /**
     * 转换实体为响应DTO
     * 
     * @param paymentType 支付方式实体
     * @return 支付方式响应DTO
     */
    private PaymentTypeResponse convertToResponse(PosPaymentType paymentType) {
        PaymentTypeResponse response = new PaymentTypeResponse();
        BeanUtils.copyBeanProp(response, paymentType);
        return response;
    }
}
